package com.ckv.qcm.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ckv.qcm.model.Trainee;
import com.google.gson.Gson;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rd = null;
		String ret = "-1";
		try {
			String name = request.getParameter("username");
			String password = request.getParameter("password");
			System.out.println(name + " / " + password);
			Trainee user = Trainee.find(name, password);

			if (user == null) {
				//requestDispatcher = "html/login_error.html";
			} else {
				HttpSession session = request.getSession();
				Gson gson = new Gson();
				ret = gson.toJson(user);
				session.setAttribute("user", user);
			}

		} catch (Exception e) {
			e.printStackTrace();
			//requestDispatcher = "html/server_error.html";
		} finally {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.flush();
			out.close();
		}
	}

}
